﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using System.Collections;
using System.Data;

namespace Fjaspx.ServerControls
{
    public class WebRepeater  : _Repeater
    {
        //私有变量
        private string mstrEmptyText = "<!--DataSource为空！Fjaspx!NT-->";//DataSource为空的时候显示的字
        private IList dataSource;//数据源，必须可以转换为IList
        private int intItemCount;

        //自定义绑定
        private int _Top = 10;//显示条数 
        private string _Son =null;//是否检索子类信息
        private int _Switchs = 0;//审核 
        private int _Tuijian = 1;//推荐 
        private int _Ding = 1;//置顶
        private string _Tag = null;//标签
        private string _Class = null;//分类ID
        private string  _StrWhere = null;//查询条件
        private string _SQL = null;//SQL语句
        private string _FiledOrder = "bh DESC";//排序规则

        public int Top
        {
            get { return _Top; }
            set { _Top = value; }
        }
        public string Son
        {
            get { return _Son; }
            set { _Son = value; }
        }
        public int Switchs
        {
            get { return _Switchs; }
            set { _Switchs = value; }
        }
        public int Tuijian
        {
            get { return _Tuijian; }
            set { _Tuijian = value; }
        }
        public int Ding
        {
            get { return _Ding; }
            set { _Ding = value; }
        }
        public string Tag
        {
            get { return _Tag; }
            set { _Tag = value; }
        }
        public string StrWhere
        {
            get {
                if (_StrWhere != null)
                {
                    if (Page.Request["path"] != null)
                    { _StrWhere = _StrWhere.Replace("{path:id}".ToLowerInvariant(), new Fjaspx.Sys.Bll.ROYcms_class().GetId("{cmspath}/" + Page.Request["path"] + "/")); }

                    Regex r = new Regex(@"\{(?<Name>\w+)\}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    foreach (Match m in r.Matches(_StrWhere))
                    {
                        string Name = m.Groups["Name"].ToString();
                        _StrWhere = _StrWhere.Replace("{" + Name.ToLowerInvariant() + "}", Page.Request[Name.ToLowerInvariant()]);
                    }
                }
                return _StrWhere;
            }
            set {
                _StrWhere = value; 
            
            }
        }
        public string SQL
        {
            get
            {
                if (_SQL != null)
                {
                    Regex r = new Regex(@"\{(?<Name>\w+)\}", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    foreach (Match m in r.Matches(_SQL))
                    {
                        string Name = m.Groups["Name"].ToString();
                        _SQL = _SQL.Replace("{" + Name.ToLowerInvariant() + "}", Page.Request[Name.ToLowerInvariant()]);
                    }
                }
                return _SQL;
            }
            set
            {
                _SQL = value;

            }
        }
        public string FiledOrder
        {
            get
            {
                return _FiledOrder;
            }
            set
            {
                _FiledOrder = value;
            }
        }
        public string Class
        {
            get
            {
                return _Class;
            }
            set
            {
                _Class = value;
            }
        }
        /**//// <summary>
        /// 数据源为空时显示的文本，默认为空
        /// </summary>
        public string EmptyText
        {
            set { mstrEmptyText = value; }
        }
        /**//// <summary>
        /// 设置 MyRepeater 控件的数据源。
        /// 可以接受 DataSet、DataTable和所以实现了IList借口的数据源。
        /// </summary>
        public override object DataSource
        {
            set
            {
                try
                {
                    if(value == null)
                    {
                        dataSource = null;
                        intItemCount = 0;
                    }
                    else if(value.GetType() == typeof(DataTable))//数据源是DataTable，转化为IList
                    {
                        dataSource = (IList)(new DataView((DataTable)value));
                        intItemCount = dataSource.Count;
                    }
                    else if(value.GetType() == typeof(DataSet))//数据源是DataSet，转化为IList
                    {
                        dataSource = (IList)(new DataView(((DataSet)value).Tables[0]));
                        intItemCount = dataSource.Count;
                    }
                    else
                    {
                        dataSource = (IList)value;
                        intItemCount = dataSource.Count;
                    }
                }
                catch
                {
                    dataSource = null;
                    intItemCount =0;
                }
            }

        }

        protected override void OnLoad(EventArgs e)
        {
            if(Visible) 
            {
                this.DataBind();
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            if(intItemCount == 0)//数据源为空
            {
                writer.Write(mstrEmptyText);
                return;
            }
            base.Render(writer);
        }

        protected override void OnDataBinding(EventArgs e)
        {
            string Strs = null;
            DataSet DS = null;
            //数据调用逻辑
            if (this.SQL != null)
            {
                DS = Fjaspx.Sys.Bll.Page.GetList(this.SQL);
            }
            else
            {   
                if (this.StrWhere == null)
                {
                    if (this.Class != null)
                    {
                        if (this.Class.Contains("|")) { Strs = Wheres(); }
                        else
                        {
                            if (this.Son == "true") { Strs = ClassWheres(); }
                            else { Strs = " classname='" + this.Class + "' "; }
                        }
                        if (this.Tag != null)
                        {
                            this.StrWhere = String.Format(Strs + " AND switchs={0}  AND ding={1}  AND tuijian={2} AND tag in ('{3}')", this.Switchs, this.Ding, this.Tuijian, this.Tag.Replace('，', ','));
                        }
                        else {
                            //过滤|转换成SQL or语句
                            this.StrWhere = String.Format(Strs + " AND (switchs={0})  AND (ding={1})  AND (tuijian={2}) ", this.Switchs, this.Ding, this.Tuijian);
                        }
                    }
                    else { this.StrWhere = String.Format(this.StrWhere + " switchs={0}  AND ding={1}  AND tuijian={2} ", this.Switchs, this.Ding, this.Tuijian); }       
                }
                DS = new Fjaspx.Sys.Bll.ROYcms_news().GetList(Top, this.StrWhere, FiledOrder);
            }
            
            //数据调用逻辑结束

            dataSource = (IList)(new DataView(((DataSet)(DS)).Tables[0]));
            base.DataSource = dataSource;
            intItemCount = dataSource.Count;
            base.OnDataBinding(e);
        }
        public string Wheres()
        {
            string Strs = null;
            string[] Str = null;
            if (this.Class.Contains("|")) { Str = this.Class.Split('|'); }
            for (int i = 0; i < Str.Length; i++) 
            {
                Strs += " (classname='" + Str[i] + "') OR";
            }
            return Strs.Substring(0, Strs.Length - 2);
        }
        public string ClassWheres()
        {
            string Strs = null;
            Fjaspx.Sys.Bll.ROYcms_class Bll = new Fjaspx.Sys.Bll.ROYcms_class();
            DataSet DS = Bll.GetSubClassList(Bll.GetClassId(Convert.ToInt32(this.Class)));

            DataTable dt = DS.Tables[0];
            //遍历行
            if (dt.Rows.Count < 1) { Strs = " classname='" + this.Class + "' "; }
            else
            {
                foreach (DataRow dr in dt.Rows)
                {
                    Strs += " (classname='" + dr["Id"].ToString() + "') OR";
                }
               Strs = Strs.Substring(0, Strs.Length - 2);
            }
            return Strs;
        }

    }
}
